//
//  HNAPayURLRequest.m
//  HNAPayMobileSDK
//
//  Created by Ly_work on 15/11/19.
//  Copyright © 2015年 usolv. All rights reserved.
//

#import "HNAPayURLRequest.h"
#import "HNAPayDefaultDefine.h"

@implementation HNAPayURLRequest

+ (HNAPayURLRequest *)creatRequestWithURL:(NSString *)urlString method:(NSString *)method parameter:(NSDictionary *)parameters encoding:(NSStringEncoding)encoding
{
    HNAPayURLRequest *request = [HNAPayURLRequest requestWithURL:[NSURL URLWithString:urlString]];
//    request.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
    [request setHTTPMethod: method];
    [request setHTTPBody: [request createPostBodyDataWithParameters:parameters encoding:encoding]];
    return  request;
}

-(NSString *)creatStringWithParameters:(NSDictionary *)parameters
{
    if (parameters) {
        __block NSMutableString *parametersString = [NSMutableString string];
        parametersString = nil;
        NSString *charactersToEscape = @"?!@#$^&%*+,:;='\"`<>()[]{}/\\| ";
        NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
        [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {

            NSMutableString *keyValueString = [NSMutableString stringWithFormat:@"%@=%@",[key stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters],[obj stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters]];
            if (!parametersString) {
                parametersString = keyValueString;
            }else{
                [parametersString appendFormat:@"&%@",keyValueString];
            }
        }];
        return parametersString;
    }
    else{
//        NSLog(@"WARMING!!!!=====parameters nil");
        return nil;
    }
}
-(NSData *)createPostBodyDataWithParameters:(NSDictionary *)parameters encoding:(NSStringEncoding)encoding
{
    NSData *bodyData = nil;
    NSString *bodyString = [self creatStringWithParameters:parameters];
//    NSLog(@"createPostBodyData:%@",bodyString);
    if (bodyString != nil && ![bodyString isEqualToString:@""]) {
        //默认使用UTF8
        bodyData = [bodyString dataUsingEncoding: encoding];
        return bodyData;
    }
    return nil;
}

@end
